/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-03-05 11:22:02
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-20 14:12:11
 */
// pages/mine/edit.js
import {
  userAPI
} from './../../../api/user'
import {
  returnStatus,
  returnStatusToast,
  UploadFile
} from './../../../utils/index'
var appInst =  getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showSex: false,
    sexItems: [
      '女', '男', '其他'
    ],
    gender: '男',
    birthday: '1992-01-01',
    showPopup: false,
    editNick: false,
    editIntr: false,
    invitationCode: '',
    showPopup: false,
    initForm: {},
    popupTitle: '',
    form: {},
    customerTag:[],
    avatarUrl:'',
    navbarData:{
      showCapsule: 1,
      back: true
    }
  },
  onBack(){
    const {showPopup} = this.data
    if(!showPopup){
      wx.navigateBack()
    }else{
      this.setData({
        showPopup: false,
        'navbarData.title':'信息编辑'
      })
    }
  },
  // 上传头像图片
  async handleImage({
    detail
  }) {
    const {
      file
    } = detail
    const _this = this
    wx.navigateTo({
      url: '/pages/cropper/index',
      events: {
        async cropperSuccess({data}){
          // 执行上传操作
          _this.setData({
            isProgress: true,
            showCropper: false
          })
          setTimeout(() => {
          wx.showLoading({
            title: '正在上传..',
        });
          }, 800);
          const _ = await UploadFile.upload(data, 'AVATAR')
          if (_) {
            _this.setData({
              'initForm.avatarUrl':_,
              avatarUrl:_
            })
            _this.onSave()
          }

        }
      },
      success(res){
        res.eventChannel.emit('propsObj', 
        { data: {
          imagePath:file.path,
          aspectRatio:1,
          backUrl:'/pages/mine/edit/index'
        } }
        // { data: {
        //   imagePath: file.path,
        //   aspectRatio: 1,
        //   backUrl:'/pages/mine/edit/index'
        // } }
        )
      }

    })
  },
  bindPickerChange(e) {
    this.setData({
      sex: this.data.sexItems[e.detail.value]
    })
  },
  bindDateChange(e) {
    this.setData({
      birthday: e.detail.value
    })
  },
  openSex() {
    this.setData({
      showSex: true
    })
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail
    });
  },
  openDate() {
    this.setData({
      showDate: true
    })
  },
  onSelectTag({detail}){
    this.setData({
      customerTag:detail
    })    
  },
  openCamera(){
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          src: res.tempImagePath
        })
      }
    })
  },
  showNick({
    detail
  }) {
    this.setData({
      saveType: 'nickname',
      showPopup: true,
      'navbarData.title': '修改昵称',
      'form.nickname': this.data.initForm.nickname
    })
  },
  showIntr() {
    this.setData({
      saveType: 'remark',
      showPopup: true,
      'navbarData.title': '修改简介',
      'form.remark': this.data.initForm.remark
    })
  },
  showTag() {
    userAPI.queryTagByAll().then(async _ => {
      const res = await returnStatus(_)
      userAPI.handleCustomerTags().then(async _ => {
        let customerTag = await returnStatus(_)
        customerTag = customerTag.map(item=>{
          return item+''
        })
        let tags = {}
        if (res) {
          // 对tag进行分组
          for (const r of res) {
            if (!tags[r.clazz]) {
              tags[r.clazz] = []
            }
            tags[r.clazz].push(r)
          }
          this.setData({
            showPopup: true,
            saveType: 'tag',
            popupTitle: '修改个人标签',
            tags,
            customerTag
          })
        }
      })
    })

  },
  onChooseTag() {

  },
  onCancel() {
    this.setData({
      showPopup: false
    })
  },
  toInfo(){
    wx.navigateTo({
      url: `/pages/mine/home/index?customerId=${this.data.initForm.customerId}`,
    });
  },
  // 保存提交信息
  onSave(e={target:{dataset:{}}}) {
    const {
      value
    } = e.detail || {}
    const {
      type
    } = e.target.dataset
    if (type === 'tag') {
      const tagIds = this.data.customerTag.map(item=>{return item*=1})
      userAPI.handleCustomerTags(tagIds).then(async _=>{
        const res = returnStatus(_)
        if(res){
          this.setData({
            showPopup:false
          })
        }
      })
      return
    }
    if (value) {
      if (type == 'gender') {
        this.setData({
          gender: value == 0 ? '女' : value == 1 ? '男' : '其他'
        })
      }
      if (type == 'birthday') {
        this.setData({
          birthday: value
        })
      }
      (this.data.form[type] = value)
    }
    for (const o in this.data.initForm) {
      if (o != type)
        this.data.form[o] = this.data.initForm[o]
    }
    userAPI.updateCustomerInfo({
      ...this.data.form
    })
    const tempObj = `initForm.${type}`
    this.setData({
      showPopup: false,
      [tempObj]: this.data.form[type]
    })
    wx.setStorageSync('userInfo', this.data.initForm);
  },
  // 输入用户昵称
  onInputChange({
    detail,
    target
  }) {
    const {
      type
    } = target.dataset
    const tempType = `form.${type}`
    this.setData({
      [tempType]: detail
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    appInst.setTitle('信息编辑')
    // 读取缓存中的个人信息数据
    const info = wx.getStorageSync('userInfo');
    this.setData({
      invitationCode: info.invitationCode,
      initForm: info,
      avatarUrl: info.avatarUrl,
      gender: info.gender == 0 ? '女' : info.gender == 1 ? '男' : '其他'
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})